
<script setup>
import * as XLSX from 'xlsx';
import * as echarts from 'echarts'
import { ref, reactive, computed, onMounted, nextTick } from 'vue';
// ********************************** 以下勿动 **********************************
const dragNums = reactive({
  leftBarWidth: 300,
  startX: 0,
  lastX: 300,
  topBarHeight: 220,
  startY: 30,
  lastY: 220,
})

// LEFT X
const mouseDownX = (e) => {
  dragNums.startX = e.clientX
  mouseMoveX(e)
  mouseUpX()
  document.addEventListener('mousemove', mouseMoveX,  { passive: false })
  document.addEventListener('mouseup', mouseUpX,  { passive: false })
}
const mouseUpX = () => {
  dragNums.leftBarWidth = dragNums.lastX
  document.removeEventListener('mousemove', mouseMoveX,  { passive: false })
  document.removeEventListener('mouseup', mouseUpX,  { passive: false })
  resizeAllOfCharts(true)
}
const mouseMoveX = (e) => {
  e.preventDefault()
  e.stopPropagation()
  const offset = e.clientX - dragNums.startX
  if (offset !== 0 && (offset + dragNums.leftBarWidth) > 200) {
    dragNums.lastX = offset + dragNums.leftBarWidth
  }
  const isNeat = dragNums.lastX / 50 % 1 === 0
  resizeAllOfCharts(isNeat)
}
// RIGHT TOP Y
const mouseDownY = (e) => {
  dragNums.startY = e.clientY
  mouseMoveY(e)
  mouseUpY()
  document.addEventListener('mousemove', mouseMoveY,  { passive: false })
  document.addEventListener('mouseup', mouseUpY,  { passive: false })
}
const mouseUpY = () => {
  dragNums.topBarHeight = dragNums.lastY
  document.removeEventListener('mousemove', mouseMoveY,  { passive: false })
  document.removeEventListener('mouseup', mouseUpY,  { passive: false })
}
const mouseMoveY = (e) => {
  e.preventDefault()
  e.stopPropagation()
  const offset = e.clientY - dragNums.startY
  if (offset !== 0) {
    dragNums.lastY = offset + dragNums.topBarHeight
  }
}
// ********************************** 以上勿动 **********************************

import { ElMessageBox, ElMessage } from 'element-plus';
import {
  DatalibGroupVariety,
  DatalibVarietyIndexGroup,
} from '@/api/datlib/variety'
import {
  GroupIndexes,
  ExtraIndexesData,
  GroupIndexChartOptionStack,
  GroupIndexChartOptionSeason,
  GroupIndexChartOptionInterval,
  CreateCalculateFormula,
  UpdateDataIndexReading,
} from '@/api/datlib/datIndex'
import { getFirstNodeOfTree } from '@/utils/dataUtils'
import useUserInfoStore  from '@/stores/userinfo'
const userInfoStore = useUserInfoStore()

const indexTableEle = ref(null)
const chartBox1 = ref(null)
const chartBox2 = ref(null)
const chartBox3 = ref(null)
let myChart1 = null
let myChart2 = null
let myChart3 = null

  // 图形的init配置
const initChartOption = {
  graphic: {
    type: 'text',
    left: 'center',
    top: 'middle',
    silent: true,
    style: {
      fill: '#9d9d9d',
      fontWeight: 'bold',
      text: '暂无数据图形',
      fontSize: '17px'
    }
  }
}

const resizeAllOfCharts = (canDo=false) => {
  if (canDo && myChart1) {
    myChart1.resize()
  }
  if (canDo && myChart2) {
    myChart2.resize()
  }
  if (canDo && myChart3) {
    myChart3.resize()
  }
}
const pageConfigs = reactive({
  vcode: null,
  groupId: -1,
  groupTabName: 'first',
  dbTabName: 'first',
  chartColCount: 24,
  showCaculateDiag: false,
})

const groupVariety = reactive({ data: [] })
const datalibTree = reactive({
  vname: '系统指标',
  data: [],
  titleItems: [
    { id: 1, name: '系统指标', tab: 'first'},
    // { id: 2, name: '我的模板', tab: 'second'},
  ],
  activeId: 1,
})
const tableIndex = reactive({
  data: [],
  selected: [],
  lastYear: 3,
  startDate: null,
  endDate: null,
  q_start: null,
  q_end: null
})

const indexChart = reactive({
  option1: {},
  option2: {},
  option3: {},
  optionLoading: false,
  chartModeName: '小图模式',
  seriesNames: [],
  selectSeriesName: '',
  selectSeriesChart: 'line',
  selectSeriesAxis: 0

})
const indexDetail = reactive({
  rows: [],
  columns: [],
  page: 1,
  pageSize: 30,
  rowStart: 0,
  rowEnd: 30,
  dbLoadng: false,
  downloading: false,
})

const calcuteDialog = reactive({
  indexList: [],
  constantNum: '',
  activeId: -1,
  calcResultName: '',
  calcResultUnit: '',
  formulaPlain: '请构建表达式',
  formula: '',
  isApply: false,
  saveFormulaLoading: false,
})

const canOperationView = computed(() => {
  return tableIndex.selected.length > 0 
})
// 鼠标进入分组
const mouseEnterGroup = (gKey) => {
  groupVariety.data.forEach((g) => {
    g.subShow = g.key === gKey ? true : false
  })
}
// 鼠标离开分组
const mouseLeaveGroup = () => {
  mouseEnterGroup('0') // 鼠标向上离开菜单，隐藏子菜单
}

const getVarietyDatalibGroups = async (pid=0) => {
  if (!pageConfigs.vcode) return []
  const resData = await DatalibVarietyIndexGroup(pageConfigs.vcode, pid)
  return resData.data.data
}

const toSwitchDatalibTree = (titem) => {
  datalibTree.activeId = titem.id
  pageConfigs.groupTabName = titem.tab
}

// 懒加载指标分组
const lazyLoadIndexGroup = async (nodeItem, resolve) => {
  // console.log(nodeItem)
  const nodeData = nodeItem.data
  pageConfigs.vcode = nodeData.variety
  if (!nodeData || !pageConfigs.vcode) return
  let resolveData = await getVarietyDatalibGroups(nodeData.id)
  // console.log('123', resolveData)
  if (resolveData.length < 1) {
    // 获取组下的指标数据
    pageConfigs.groupId = nodeData.id
    const indexRes = await GroupIndexes(nodeData.id)
    resolveData = indexRes.data.data.map((item) => {
      item.leaf = true
      item.is_index = true
      return item
    })
  }
  // console.log('数据列表:', resolveData)
  return resolve(resolveData)
}

// 点击某个品种
const toShowVarietyDatalib = async (gKey, vItem) => {
  // console.log(gKey, vItem)
  mouseEnterGroup(gKey + 'close')
  datalibTree.titleItems[0].name = '系统指标'
  if (!vItem.access) {
    ElMessageBox.alert(`您还没有【${vItem.name}】品种的数据库权限，请联系客服开通...`)
    return
  }
  pageConfigs.vcode = vItem.code
  datalibTree.data = []
  datalibTree.data = await getVarietyDatalibGroups()
  datalibTree.titleItems[0].name = vItem.name
}

const toCollectIndex = (idx) => {
  // console.log(idx)
  tableIndex.data.push({
    id: idx.id,
    iid: idx.iid,
    name: idx.name,
    frequency: idx.frequency,
    unit: idx.unit,
    source: idx.source,
    formula: idx.iid ? idx.tb_name.split('_')[1].toUpperCase() : idx.formula,
    start_date: idx.start_date,
    end_date: idx.end_date,
  })
  indexTableEle.value?.setScrollTop(27 * tableIndex.data.length)
  if (!idx.is_formula && idx.iid) {
    // console.log('发送热度增加请求')
    UpdateDataIndexReading(idx.iid)
  }
}

const tableIndexRowClick = (row) => {
  indexTableEle.value?.clearSelection()
  indexTableEle.value?.toggleRowSelection(row, true)
}

const tableSelectChange = () => {
  tableIndex.selected = indexTableEle.value?.getSelectionRows().map((row) => row.id)
  setIndexDateRange()
}

const setIndexDateRange = () => {
  const selectRows = indexTableEle.value?.getSelectionRows()
  let eDate = null
  let sDate = null
  selectRows.forEach((item) => {
    if (!eDate || eDate < item.end_date) {
      eDate = item.end_date
    }
    if (!sDate || sDate > item.start_date) {
      sDate = item.start_date
    }
  })
  tableIndex.startDate = sDate
  tableIndex.endDate = eDate
}

const initPageMounted = async () => {
  try {
    const resData = await DatalibGroupVariety()
    groupVariety.data = resData.data.data.map((item) => {
    item.subShow = false
    return item
  })
  } catch (err){
    return
  }
  datalibTree.titleItems[0].name = '系统指标'
  if (groupVariety.data.length > 0) {
    const first = getFirstNodeOfTree(groupVariety.data, 'varieties')
    if (first) { 
      toShowVarietyDatalib(first.group_id, first)
      datalibTree.titleItems[0].name = first.name
    }
  }
}

const toggleChartSize = () => {
  if (pageConfigs.chartColCount === 24) {
    pageConfigs.chartColCount = 12
    indexChart.chartModeName = '大图模式'
  } else {
    pageConfigs.chartColCount = 24
    indexChart.chartModeName = '小图模式'
  }
  nextTick(() => {
    myChart1.resize()
    myChart2.resize()
  })
}

const toViewCharts = () => {
  if (tableIndex.selected.length > 3) {
      ElMessage.warning('我们建议您可视化小于3个指标图形。')
  }
  if (tableIndex.selected.length > 10) {
    ElMessageBox({
      message: '一次可视化指标过多，请减少至10个以下再尝试!',
      type: 'error',
      title: '错误了'
    })
    return
  }

  tableIndex.q_start = null
  tableIndex.q_end = null
  tableIndex.lastYear = 3

  pageConfigs.dbTabName = 'first'
  setChartOption_1()
  setChartOption_2()
  setChartOption_3()
}
const toExtraDatas = () => {
  if (tableIndex.selected.length > 10) {
    ElMessageBox({
      message: '一次可视化指标过多，请减少至10个以下再尝试!',
      type: 'error',
      title: '错误了'
    })
    return
  }
  pageConfigs.dbTabName = 'second'
  indexDetail.dbLoadng = true
  ExtraIndexesData({
    extra_ids: tableIndex.selected
  }).then((res) => {
    // console.log(res)
    indexDetail.rows = res.data.table_data
    indexDetail.columns = res.data.table_columns
    indexDetail.dbLoadng = false
  }).catch(() => { indexDetail.dbLoadng = false })
}

const toCaculateRows = () => {
  calcuteDialog.indexList = indexTableEle.value?.getSelectionRows()
  for (let i=0; i < calcuteDialog.indexList.length; i++) {
    if (!calcuteDialog.indexList[i].iid) {
      ElMessageBox({
        message: '参与计算的指标中暂不支持公式，构建公式时可同时申请制作成指标，再使用系统的新指标构建公式.',
        type: 'error',
        title: '错误了'
      })
      return;
    }
  }
  pageConfigs.showCaculateDiag = true
}

const toQueryDateRange = () => {
  tableIndex.q_start = tableIndex.startDate
  tableIndex.q_end = tableIndex.endDate
  tableIndex.lastYear = -1
  setChartOption_1()
  // setChartOption_2()
  // setChartOption_3()
}

const toDownloadDetail = () => {
  // 重新构建数据,才有中文表头
  indexDetail.downloading = true
  let excelData = []
  for (let i=0; i< indexDetail.rows.length; i ++) {
    let row = indexDetail.rows[i]
    let nrow = {'日期': row['datadate']}
    for (let j=0; j < indexDetail.columns.length; j++) {
      let col = indexDetail.columns[j]
      nrow[col.label] = row[col.prop]
    } 
    excelData.push(nrow)
  }
  let wb = XLSX.utils.book_new()
  let ws = XLSX.utils.json_to_sheet(excelData, { skipHeader: false})
  let timestamp = new Date().getTime()
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
  XLSX.writeFile(wb, timestamp + '.xlsx')
  indexDetail.downloading = false
}

const setChartOption_1 = () => {
  myChart1.showLoading({ text: '正在可视化' })
  GroupIndexChartOptionStack(
    tableIndex.selected.join(','),
    tableIndex.lastYear,
    tableIndex.q_start,
    tableIndex.q_end,
  ).then((res) => {
    indexChart.option1 = res.data.option
    myChart1.setOption(indexChart.option1, { notMerge: true })
    myChart1.hideLoading()
    myChart1.resize()

    // console.log(indexChart.option1)
    indexChart.seriesNames = []
    for (let i=0; i < indexChart.option1.series.length; i++) {
      indexChart.seriesNames.push(indexChart.option1.series[i].name)
    }
    if (indexChart.seriesNames.length > 0) {
      indexChart.selectSeriesName = indexChart.seriesNames[0]
    }
  })
}

const setChartOption_2 = () => {
  myChart2.showLoading({ text: '拼命加载季节图' })
  GroupIndexChartOptionSeason(
    tableIndex.selected[0],
  ).then((res) => {
    indexChart.option2 = res.data.option
    myChart2.setOption(indexChart.option2, { notMerge: true })
    myChart2.hideLoading()
    myChart2.resize()
  })
}

const setChartOption_3 = () => {
  myChart3.showLoading({ text: '拼命加载区间图'})
  GroupIndexChartOptionInterval(
    tableIndex.selected[0],
  ).then((res) => {
    indexChart.option3 = res.data.option
    myChart3.setOption(indexChart.option3, { notMerge: true })
    myChart3.hideLoading()
    myChart3.resize()
  })
}

const chartConfigChanged = () => {
  if (!indexChart.option1.series || indexChart.option1.series.length < 1) return
  const seriesData = JSON.parse(JSON.stringify(indexChart.option1.series))
  // console.log(seriesData)
  for (let i = 0; i < seriesData.length; i++) {
    const sd = seriesData[i]
    if (sd.name === indexChart.selectSeriesName) {
      sd.yAxisIndex = indexChart.selectSeriesAxis
      sd.type = indexChart.selectSeriesChart
    }
  }
  // console.log(seriesData)
  indexChart.option1.series = seriesData
  myChart1.setOption(indexChart.option1, { notMerge: true })
}

const indexDetailPageChange = (p) => {
  indexDetail.page = p
  indexDetail.rowStart = (p - 1) * indexDetail.pageSize
  indexDetail.rowEnd = indexDetail.rowStart + indexDetail.pageSize
}

const resetFormulaPlain = () => {
  calcuteDialog.formula = ''
  calcuteDialog.constantNum = ''
  calcuteDialog.formulaPlain = '请构建表达式'
  calcuteDialog.calcResultName = ''
  calcuteDialog.calcResultUnit = ''
}

const buildCalculateFormula = (item) => {
  const isObj = Object.prototype.toString.call(item) === '[object Object]'
  if (calcuteDialog.formulaPlain === '请构建表达式') {
    calcuteDialog.formulaPlain = ''
    calcuteDialog.formula = ''
  }
  if (isObj) {
    calcuteDialog.formulaPlain += item.name
    calcuteDialog.formula += 'i' + item.iid
  } else {
    if (item === '0') {
      calcuteDialog.formulaPlain += calcuteDialog.constantNum + ''
      calcuteDialog.formula += calcuteDialog.constantNum + ''
    } else {
      calcuteDialog.formulaPlain += ' ' + item + ' '
      calcuteDialog.formula += item
    }
  }
}

const toSaveMyFormula = () => {
  const formualItem = {
    vcode: pageConfigs.vcode,
    group_id: pageConfigs.groupId,
    name: calcuteDialog.calcResultName.trim(),
    formula: calcuteDialog.formula.trim(),
    unit: calcuteDialog.calcResultUnit.trim(),
    apply: calcuteDialog.isApply,
  }
  if (formualItem.apply && !formualItem.name) {
    ElMessage.error('申请制作为指标请录入一个名称!')
    return
  }
  if (!formualItem.apply && !formualItem.name) {
    formualItem.name = '我的临时计算'
  }
  calcuteDialog.saveFormulaLoading = true
  CreateCalculateFormula(formualItem).then((res) => {
    tableIndex.data.push(res.data)
    pageConfigs.showCaculateDiag = false
    ElMessage.success('设置公式成功!')
    calcuteDialog.saveFormulaLoading = false
  }).catch(() =>{
    calcuteDialog.saveFormulaLoading = false
  })
}

onMounted(() => {
  initPageMounted()
  myChart1 = echarts.init(chartBox1.value)
  myChart1.setOption(initChartOption)
  myChart2 = echarts.init(chartBox2.value)
  myChart2.setOption(initChartOption)
  myChart3 = echarts.init(chartBox3.value)
  myChart3.setOption(initChartOption)
})
</script>
<template>
<div class="page-view">
  <div class="variety-group">
    <div
      v-for="group in groupVariety.data"
      :key="group.key"
      class="g-item"
      @mouseenter="mouseEnterGroup(group.key)"
      @mouseleave="mouseLeaveGroup()"
    >
      <span class="g-name">{{ group.name }}</span>
      <div :class="group.subShow ? 'group-sub sub-show':'group-sub'">
        <div class="v-box">
          <div
            v-for="v in group.varieties"
            :key="v.code"
            :class="v.access ? 'v-item' : 'v-item no-access' "
            @click="toShowVarietyDatalib(group.key, v)"
          >{{ v.name }}</div>
        </div>
      </div>
    </div>
  </div>

  <div class="out-box">
    <div class="left-box" :style="{ width: `${dragNums.lastX}px`}">
      <div class="x-resizer" @mousedown="mouseDownX">⋮</div>
      <div class="tree-top">
        <div
          v-for="titem in datalibTree.titleItems"
          :key="titem.id"
          :class="datalibTree.activeId === titem.id ? 'top-item-active' : 'top-item'"
          @click="toSwitchDatalibTree(titem)"
        >
          {{ titem.name }}
        </div>
      </div>
      <div class="search-box" v-show="false">
        <el-select
          style="width: 100%;"
          placeholder="检索指标"
          size="default"
          no-data-text="输入关键词检索指标"
        ></el-select>
      </div>
      <div style="height: 10px"></div>
      <el-scrollbar class="tree-scroll">
        <el-tabs v-model="pageConfigs.groupTabName">
          <el-tab-pane name="first">
            <el-tree
              lazy
              empty-text="暂无数据"
              node-key="id"
              :indent="8"
              :props="{ isLeaf: 'leaf' }"
              :load="lazyLoadIndexGroup"
              :data="datalibTree.data"
            >
              <template #default="{ data }">
                <div
                  v-if="data.is_index"
                  class="index-node"
                  @dblclick="toCollectIndex(data)"
                >
                  <div class="icon-name">
                    <el-icon v-if="data.is_private">
                      <UserFilled />
                    </el-icon>
                    <el-icon v-else>
                      <Tickets />
                    </el-icon>
                    {{ data.name }}
                  </div>
                  <div class="actions">
                    <el-icon @click="toCollectIndex(data)"><Plus /></el-icon>
                  </div>
                </div>
                <div v-else>
                  {{ data.name }}
                </div>
              </template>
            </el-tree>
          </el-tab-pane>
          <el-tab-pane name="second">
            <div style="color: #666; text-align: center;">我的模板暂未开放</div>
          </el-tab-pane>
        </el-tabs>
        
      </el-scrollbar>
    </div>

    <div class="right-box">
      <div class="right-top-box" :style="{ height: `${dragNums.lastY}px` }">
        <div class="y-resizer" @mousedown="mouseDownY">···</div>
        <el-table
          stripe
          border
          ref="indexTableEle"
          row-class-name="table-row"
          empty-text="暂无数据指标"
          class="index-table"
          :highlight-current-row="true"
          :data="tableIndex.data"
          @row-click="tableIndexRowClick"
          @selection-change="tableSelectChange"
        >
          <el-table-column type="selection" width="30" />
          <el-table-column prop="name" label="指标名称" show-overflow-tooltip />
          <el-table-column prop="formula" label="公式" width="150" show-overflow-tooltip align="center" />
          <el-table-column prop="frequency" label="频率" width="120" show-overflow-tooltip align="center" />
          <el-table-column prop="unit" label="单位" width="120" show-overflow-tooltip align="center" />
          <el-table-column prop="start_date" label="开始时间" width="100" show-overflow-tooltip align="center" />
          <el-table-column prop="end_date" label="结束时间" width="100" show-overflow-tooltip align="center" />
        </el-table>
      </div>
      <div class="right-bottom-box">
        <div class="data-actions">
          <el-button
            plain
            :disabled="!canOperationView"
            :loading="indexChart.optionLoading"
            @click="toViewCharts"
          >
            <span>数据可视化</span>
            <span v-if="canOperationView">({{ tableIndex.selected.length }})</span>
          </el-button>
          <el-button
            plain
            :disabled="!canOperationView"
            :loading="tableIndex.dbLoadng"
            @click="toExtraDatas"
          >
            <span>提取数据</span>
            <span v-if="canOperationView">({{ tableIndex.selected.length }})</span>
          </el-button>
          <el-button plain @click="toggleChartSize">{{ indexChart.chartModeName }}</el-button>
          
          <div class="actions-right">
            <el-button
              plain
              :disabled="!canOperationView"
              @click="toCaculateRows"
            >
              指标运算
            </el-button>
            <el-button
              v-if="userInfoStore.isVip"
              v-show="pageConfigs.dbTabName === 'second'"
              plain
              icon="Download"
              :loading="indexDetail.downloading"
              @click="toDownloadDetail"
            >
              下载数据
            </el-button>
            <el-button
              plain
              icon="Delete"
              @click="tableIndex.data = []"
            >
              清空指标
            </el-button>
          </div>
        </div>
        <div class="scroll-view" :style="{ height: `calc(100vh - 99px - ${dragNums.lastY}px)`}">
          <el-scrollbar>
            <div v-show="pageConfigs.dbTabName === 'first'" class="chart-config">
              <el-icon><Calendar /></el-icon>
              <el-date-picker
                v-model="tableIndex.startDate"
                class="date-picker"
                value-format="YYYY-MM-DD"
                :clearable="false"
                :editable="false"
              />
              <span>~</span>
              <el-date-picker
                v-model="tableIndex.endDate"
                class="date-picker"
                value-format="YYYY-MM-DD"
                :clearable="false"
                :editable="false"
              />
              <el-button
                type="primary"
                style="margin-left: 5px;"
                :disabled="!canOperationView"
                @click="toQueryDateRange"
              >
                查询
              </el-button>
              <div class="right-bar">
                <el-select
                  v-model="indexChart.selectSeriesName"
                  class="select-item"
                  style="width: 200px"
                  placeholder="请选择指标"
                  @change="chartConfigChanged"
                >
                  <el-option
                    v-for="(sname, idx_name ) in indexChart.seriesNames"
                    :key="idx_name"
                    :value="sname"
                    :label="sname"
                  />
                </el-select>
                <div>以</div>
                <el-select 
                  v-model="indexChart.selectSeriesChart"
                  class="select-item"
                  @change="chartConfigChanged"
                >
                  <el-option value="line" label="折线图" />
                  <el-option value="bar" label="柱形图" />
                </el-select>
                <div>放置于</div>
                <el-select
                  v-model="indexChart.selectSeriesAxis"
                  class="select-item"
                  @change="chartConfigChanged"
                >
                  <el-option :value="0" label="左轴" />
                  <el-option :value="1" label="右轴" />
                </el-select>
              </div>
            </div>
            <el-tabs v-model="pageConfigs.dbTabName">
              <el-tab-pane name="first">
                <el-row class="chart-row" :gutter="8">
                  <el-col :span="pageConfigs.chartColCount">
                    <div ref="chartBox1" class="chart-item">
                      普通图形
                    </div>
                  </el-col>
                  <el-col :span="pageConfigs.chartColCount">
                    <div ref="chartBox2" class="chart-item">
                      季节图形
                    </div>
                  </el-col>
                </el-row>
                <el-row class="chart-row" :gutter="8">
                  <el-col :span="24">
                    <div ref="chartBox3" class="chart-item">
                      区间图形
                    </div>
                  </el-col>
                </el-row>
              </el-tab-pane>
              <el-tab-pane name="second">
                <div class="db-rows">
                  <el-table
                    highlight-current-row
                    scripe
                    border
                    :data="indexDetail.rows.slice(indexDetail.rowStart, indexDetail.rowEnd)"
                  >
                    <el-table-column prop="datadate" label="日期" width="110">
                      <template #header>
                        <div>
                          <div>日期</div>
                          <div>频率</div>
                          <div>单位</div>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column
                      v-for="col in indexDetail.columns"
                      :key="col.prop"
                      :prop="col.prop"
                      :label="col.label"
                    >
                      <template #header>
                        <div>
                          <div class="name-label">{{ col.label }}</div>
                          <div>{{ col.frequency }}</div>
                          <div>{{ col.unit }}</div>
                        </div>
                      </template>
                    </el-table-column>
                  </el-table>
                  <div class="paginator">
                    <el-pagination
                      small
                      background
                      layout="total,prev,pager,next,jumper"
                      :page-size="indexDetail.pageSize"
                      :total="indexDetail.rows.length"
                      @current-change="indexDetailPageChange"
                    />
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </el-scrollbar>
        </div>
      </div>
    </div>
  </div>
  
  <div class="calculate-diag">
    <el-dialog
    v-model="pageConfigs.showCaculateDiag"
    width="800"
  >
    <template #header>
      <div class="diag-header">指标运算</div>
    </template>
    <div class="diag-body">
      <div class="b-left">
        <div>待选指标</div>
        <div class="b-index">
          <el-scrollbar>
            <div
              v-for="r in calcuteDialog.indexList"
              :key="r.id"
              :class="calcuteDialog.activeId === r.id ? 'active-item-index': 'item-index'"
              @click="calcuteDialog.activeId = r.id"
              @dblclick="buildCalculateFormula(r)"
            >
              <span class="fre-index">{{ r.frequency }}</span>
              {{ r.name }}
            </div>
          </el-scrollbar>
        </div>
      </div>
      <div class="b-right">
        <div>运算符</div>
        <div class="calc-operater">
          <el-button type="primary" @click="buildCalculateFormula('+')">+</el-button>
          <el-button type="primary" @click="buildCalculateFormula('-')">-</el-button>
          <el-button type="primary" @click="buildCalculateFormula('*')">x</el-button>
          <el-button type="primary" @click="buildCalculateFormula('/')">÷</el-button>
          <el-button type="success" @click="buildCalculateFormula('(')">(</el-button>
          <el-button type="success" @click="buildCalculateFormula(')')">)</el-button>
          <el-button @click="buildCalculateFormula('0')">常数</el-button>
          <el-input
            v-model="calcuteDialog.constantNum"
            placeholder="输入常数"
            clearable
          />
        </div>
        <div class="formula-action">
          <div>计算公式</div>
          <el-button
            link
            icon="Delete"
            type="danger"
            style="margin-left: auto"
            @click="resetFormulaPlain"
          >
            重置
          </el-button>
        </div>
        <div class="formula-box">
          {{ calcuteDialog.formulaPlain }}
        </div>
        <div class="formula-result">
          <el-input
            v-model="calcuteDialog.calcResultName"
            placeholder="给计算结果取一个指标名称"
          />
          <el-input
            v-model="calcuteDialog.calcResultUnit"
            class="result-unit"
            placeholder="计算结果单位"
          />
        </div>
      </div>
    </div>
    <div class="tips-box">
      <div>注：请使用<span style="color: red;">相同频率</span>的指标进行运算、结果会保存在最近点击而展开的组中。</div>
      <el-checkbox
        v-model="calcuteDialog.isApply"
        style="margin-left: auto"
      >
        申请制作成指标
      </el-checkbox>
    </div>
    <template #footer>
      <el-button @click="pageConfigs.showCaculateDiag = false">取消</el-button>
      <el-button type="primary" @click="toSaveMyFormula">确定保存</el-button>
    </template>
  </el-dialog>
  </div>
  
</div>   
</template>
<style lang="scss" scoped>
@keyframes showBox {
  0% {height: 0;} 100% {height: 130px;}
}
.page-view {
  height: calc(100vh - 40px);
  background-color: #f7f7f7;
  .variety-group {
    line-height: 28px;
    height: 28px;
    display: flex;
    align-items: center;
    background-color: #eee;
    .g-item{
      position: relative;
      .g-name {
        margin-left: 10px;
        font-size: 15px;
        cursor: pointer;
        &:hover {
          color: #ea5404;
        }
      }
    }
    .group-sub {
      position: absolute;
      left: 10px;
      display: none;
      background-color: #eee;
      width: 500px;
      height: 130px;
      padding: 4px 8px;
      border: 1px solid #aaa;
      z-index: 9;
      .v-box {
        display: flex;
        flex-wrap: wrap;
        .v-item {
          width: 70px;
          height: 26px;
          text-align: left;
          line-height: 26px;
          font-size: 15px;
          padding: 0 4px;
          color: #023b8f;
          cursor: pointer;
          &:hover {
            color: #ea5404;
            text-decoration: underline;
          }
        }
        .no-access {
          color: #444;
          &:hover {
            color: #333;
            text-decoration: underline;
          }
        }
      }
      
    }
    .sub-show {
      display: block;
      animation: 500ms showBox;
    }
  }
  .out-box{
    display:flex;
    height: calc(100vh - 68px);
   .left-box {
      min-width: 0px;
      max-width: 50%;
      background: #fff;
      position: relative;
      border-left: 1px solid #eee;
      border-right: 1px solid #eee;
      .x-resizer {
        position: absolute;
        top: 50%;
        right: -7px;
        z-index: 1;
        height: 40px;
        margin-top: -25px;
        border-top-right-radius: 10px;
        border-bottom-right-radius: 10px;
        cursor: col-resize;
        text-align: center;
        line-height: 40px;
        background-color: #ccc;
        font-size: 25px;
        color: #666;
        width: 7px;
        z-index: 9;
      }
      .tree-top {
        display: flex;
        align-items: center;
        padding: 0px 5px;
        font-size: 15px;
        line-height: 31px;
        border-bottom: 1px solid #eee;
        .top-item {
          padding: 0 10px;
          cursor: pointer;
          &-active {
            margin: -2px 10px;
            cursor: pointer;
            color: $goldenColor;
            border-bottom: 2px solid $goldenColor;
          }
        }
      }
      .search-box {
        height: 32px;
        margin: 10px 3px;
      }
      .tree-scroll {
        height: calc(100% - 84px);
        position: relative;
        .el-tabs ::v-deep(.el-tabs__header) {
          display:none;
        }
      }
      .index-node {
        display: flex;
        user-select: none;
        align-items: center;
        width: 100%;
        color: #000;
        background-color: #f5f7fa;
        padding: 2px 10px;
        padding-left: 5px;
        height: 26px;
        line-height: 26px;
        &:hover {
          background-color: #d5dfee;
          .info-span {
            opacity: 1;
          }
        }
        .icon-name {
          display: flex;
          align-items: center;
          .el-icon {
            margin-right: 2px;
          }
        }
        .actions {
          margin-left: auto;
        }
      }
    }
    .right-box {
      flex: 1;
      background: #fff;
      // margin-left: 1px;
      position: relative;
      border-right: 1px solid #eee;
      height: 100%;
      .right-top-box {
        position: relative;
        // background-color: #aedfea;
        border-bottom: 1px solid #eee;
        .y-resizer {
          position: absolute;
          top: 100%;
          right: 50%;
          z-index: 1;
          height: 7px;
          border-bottom-left-radius: 10px;
          border-bottom-right-radius: 10px;
          cursor: row-resize;
          text-align: center;
          line-height: 7px;
          background-color: #ccc;
          font-size: 25px;
          color: #666;
          width: 40px;
          z-index: 1;
        }
        .index-table {
          position: absolute;
          height: 100%;
          color: #000;
          font-size: 14px;
          cursor: default;
        }
      }
      .right-bottom-box {
        // background-color: #eeadee;
        position: relative;
        .data-actions {
          height: 30px;
          display: flex;
          align-items: center;
          padding-left: 10px;
          background: linear-gradient(to bottom,#eee,#fff, #eee);
          .actions-right{
            margin-left: auto;
          }
          ::v-deep(.el-button) {
            margin-left: 0;
            padding: 5px 7px;
            border:none;
            color: #222;
            background-color: rgba(238, 238, 200, 0);
            &:focus-visible {
              outline: 0;
            }
            &:hover {
              color: $goldenColor;
            }
          }
        }
        .scroll-view {
          // height: calc(100vh - 50px);
          position: absolute;
          width: 100%;
          .chart-config {
            display: flex;
            align-items: center;
            margin-top: 10px;
            padding: 0 10px;
            .el-icon {
              margin-right: 5px;
            }
            ::v-deep(.date-picker) {
              width: 90px;
              justify-content: center;
            }
            ::v-deep(.el-input__wrapper) {
              box-shadow: 0 0 0 0;
              border-bottom: 1px solid #ccc;
              border-radius: 0;
              .el-input__prefix {
                display: none;
              }
            }
            .right-bar {
              margin-left: auto;
              display: flex;
              align-items: center;
              .select-item {
                width: 80px;
                ::v-deep(.el-input__wrapper){
                  border-radius: 0;
                  box-shadow: 0 0 0 0 !important;
                  &:hover {
                    box-shadow: 0 0 0 0;
                  }
                }
              }
            }
          }
          
          .el-tabs ::v-deep(.el-tabs__header) {
            display:none;
          }
          .chart-row {
            padding: 0 10px;
            .chart-item {
              width: 100%;
              height: 350px;
              // border: 1px solid #777;
              box-shadow: 0 0 10px #ccc;
              margin-top: 10px;
            }
          }
          .db-rows {
            padding: 10px;
            .name-label {
              white-space: nowrap;
              word-wrap: normal;
            }
          }
          .paginator {
            display: flex;
            justify-content: center;
            margin-top: 10px;
          }
        }
      }
    }
  }

  .calculate-diag {
    ::v-deep(.el-dialog__header) {
      padding: 0;
      margin-right: 0;
    }
    ::v-deep(.el-dialog__headerbtn) {
      height: 40px;
    }
    ::v-deep(.el-dialog__body) {
      padding: 10px 15px;
      height: 500px;
    }
    .diag-header {
      border-bottom: 1px solid #efefef;
      background-color: #dce5f8;
      height: 40px;
      line-height: 40px;
      padding-left: 20px;
    }
    .diag-body {
      display: flex;
      // height: 400px;
      .b-left {
        position: relative;
        margin-right: 10px;
        .b-index {
          line-height: 30px;
          margin-top: 10px;
          width: 380px;
          height: 450px;
          padding: 5px 0;
          border: 1px solid #ececf7;
          background-color: #f2f2f2;
          cursor: default;
          .fre-index {
            display: inline-block;
            padding: 0px 4px;
            background-color: #dee6f8;
            border: 1px solid #3b5f96;
            line-height: 18px;
            border-radius: 5px;
          }
          .item-index {
            margin: 2px 0;
            padding: 0 10px;
            color: #222;
          }
          .active-item-index {
            background-color: #409eff;
            color: #fff;
            padding: 0 10px;
            margin: 2px 0;
            .fre-index {
              color: #222;
            }
          }
        }
      }
      .b-right {
        position: relative;
        width: 380px;
        .calc-operater{
          margin-top: 10px;
          display: flex;
          ::v-deep(.el-input__wrapper) {
            box-shadow: 0 0 0 0;
            border-bottom: 1px solid #ccc;
            border-radius: 0;
          }
        }
        .formula-action {
          margin-top: 10px;
          display: flex;
          align-items: center;
        }
        .formula-box {
          height: 352px;
          margin-top: 10px;
          padding: 5px 10px;
          border: 1px solid #ececf7;
        }
        .formula-result {
          margin-top: 10px;
          display: flex;
          align-items: center;
          .result-unit {
            width: 150px;
            margin-left: 6px;
            ::v-deep(.el-input__wrapper) {
              box-shadow: 0 0 0 0;
              border-bottom: 1px solid #ccc;
              border-radius: 0;
            }
          }
        }
      }
    }
    .tips-box {
      line-height: 26px;
      display: flex;
      align-items: center;
    }
  }
}
</style>